<?php

namespace Modules\User\Library;

use MongoDB\BSON\ObjectID;
use Phalcon\Di;
use Modules\Search\Library\Search;

class UserNameChosenSource
{
    public static function getOptions($value)
    {
        $user = Di::getDefault()->getShared('entityManager')->get('user', [
            'conditions' => [
                '_id' => new ObjectID($value)
            ]
        ]);
        if (!$user) {
            return [];
        }
        return [
            $value => $user->name
        ];
    }

    public static function ajaxSource(){
        $term = Di::getDefault()->getShared('request')->getQuery('term');
        $term = urldecode($term);

        $data = [];
        $search = new Search(WEB_CODE . '_user');
        $searchData = $search->search([
            'conditions' => $term,
            'limit' => [20, 0]
        ]);

        foreach ($searchData as $item){
            $data[] = [
                'id' => $item->id,
                'name' => $item->name
            ];
        }
        return $data;
    }
}